import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:landlore/dbUtil/databaseHelper.dart';
import 'package:landlore/screens/roomEditScreen.dart';
import 'package:path_provider/path_provider.dart';
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';

import '../customWidget/recordBody.dart';
import '../model/orderVO.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// import 'package:gallery_saver/gallery_saver.dart';
import 'dart:io';

import '../model/roomInfo.dart';

/***
 * 出单页面
 */
class OutputBillScreen extends StatefulWidget {
  final int orderId;

  OutputBillScreen({super.key, required this.orderId});

  @override
  State<OutputBillScreen> createState() => _OutputBillScreenState();
}

class _OutputBillScreenState extends State<OutputBillScreen> {
  OrderVO? orderVO;
  final ScreenshotController screenshotController = ScreenshotController();

  File? file = null;

  bool forceChangeState = false;

  TextEditingController c1 = TextEditingController();
  TextEditingController c2 = TextEditingController();
  TextEditingController c3 = TextEditingController();
  TextEditingController c4 = TextEditingController();
  TextEditingController c5 = TextEditingController();
  TextEditingController c6 = TextEditingController();
  List<TextEditingController> cList=[];

  @override
  initState() {
    super.initState();
    forceChangeState = false;
    _getOrderData();
  }

  //点击强制修改时,初始化控制器
  _initalTextController(){
    c1.text = orderVO!.rent.toString();
    c2.text = orderVO!.otherCharge.toString();
    c3.text = orderVO!.electricityAmountResult.toString();
    c4.text = orderVO!.electricityCharge.toString();
    c5.text = orderVO!.waterAmountResult.toString();
    c6.text = orderVO!.waterCharge.toString();

    setState(() {
      cList..add(c1)..add(c2)..add(c3)..add(c4)..add(c5)..add(c6);
    });
    print('控制器初始化完成');
    print(cList.length);
  }
  @override
  dispose(){
    c1.dispose();
    c2.dispose();
    c3.dispose();
    c4.dispose();
    c5.dispose();
    c6.dispose();
    super.dispose();
  }

  _getOrderData() async {
    DatabaseHelper db = DatabaseHelper.instance;
    OrderVO result = await db.getOrderByIdForBillOut(widget.orderId);
    setState(() {
      orderVO = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      ///设置文字大小不随系统设置改变
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color(0xffe9c46a),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 35.sp,
              color: Colors.black,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            "出单",
            style: TextStyle(
                decoration: TextDecoration.none,
                fontSize: 30.sp,
                color: Colors.black,
                fontWeight: FontWeight.w900),
          ),
          centerTitle: true,
          actions: [
            CupertinoButton(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Icon(Icons.settings, color: Colors.black54, size: 29.sp),
                    Text(
                      '修改',
                      style: TextStyle(fontSize: 16.sp, color: Colors.black54),
                    ),
                  ],
                ),
                onPressed: () async {
                  DatabaseHelper db = DatabaseHelper.instance;
                  RoomInfo roomInfo =
                      await db.getRoomInfoById(orderVO!.roomId!);
                  await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => RoomEditScreen(
                                roomInfo: roomInfo,
                              )));
                  _getOrderData();
                })
          ],
        ),
        body: Container(
            color: Colors.grey,
            child: ListView(
              children: orderVO == null
                  ? []
                  : [
                      Container(
                        margin: EdgeInsets.only(top: 5.h),
                        child: Text(
                          '*若用电量/用水量有误,请返回重新抄表.',
                          style: TextStyle(fontSize: 16.sp),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 5.h),
                        child: Text('*若其他费有误,请点击右上角 ⚙修改 按钮,以更新房屋基本信息',
                            style: TextStyle(fontSize: 16.sp)),
                      ),
                      Screenshot(
                          controller: screenshotController,
                          child: RecordBody(
                            orderVO: orderVO!,
                            forceChangeState: forceChangeState,
                            cList: cList,
                            callback: (result){
                              setState(() {
                                orderVO = result;
                              });
                            },
                          )),
                      Offstage(
                        offstage: forceChangeState,
                        child: Container(
                          padding: EdgeInsets.only(left: 100.w, right: 100.w),
                          margin: EdgeInsets.only(top: 40.h, bottom: 0.h),
                          height: 60.h,
                          child: ElevatedButton(
                              onPressed: () {
                                //根据 此时此刻的房屋信息 ,更新订单表,并修改状态为已出单,且标记为未付款
                                orderVO!.state = OrderState.BILL_OUT;
                                orderVO!.checkState = OrderCheckState.DEFAULT;
                                DatabaseHelper.instance.billOut(orderVO!);

                                // 保存截图为图片文件
                                // GallerySaver.saveImage(file.path, albumName: 'MyScreenshots');
                                showDialog(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return AlertDialog(
                                        content: Text(
                                          '出单成功',
                                          style: TextStyle(fontSize: 30.sp),
                                        ),
                                        actions: [
                                          TextButton(
                                              onPressed: () async {
                                                //生成图片
                                                await createImg();

                                                try {
                                                  await ImageGallerySaver.saveImage(
                                                      await file!.readAsBytes(),
                                                      name:
                                                          '${orderVO?.roomNum}账单_${orderVO?.createDate?.year}_${orderVO?.createDate?.month}');
                                                  print("Image saved to gallery");

                                                  showSnackBar(context);
                                                } catch (e) {
                                                  print(
                                                      "Failed to save image: $e");
                                                }
                                              },
                                              child: Text(
                                                '保存账单',
                                                style: TextStyle(fontSize: 25.sp),
                                              )),
                                          TextButton(
                                              onPressed: () async {
                                                //生成图片
                                                await createImg();

                                                Share.shareFiles([file!.path],
                                                    subject:
                                                        '${orderVO?.roomNum}账单_${orderVO?.createDate?.year}_${orderVO?.createDate?.month}',
                                                    text:
                                                        '${orderVO?.roomNum}账单_${orderVO?.createDate?.year}_${orderVO?.createDate?.month}');
                                              },
                                              child: Text(
                                                '分享账单',
                                                style: TextStyle(fontSize: 25.sp),
                                              )),
                                          TextButton(
                                              onPressed: () async {
                                                Navigator.pop(context);
                                                Navigator.pop(context);
                                              },
                                              child: Text(
                                                '完成',
                                                style: TextStyle(fontSize: 25.sp),
                                              )),
                                        ],
                                      );
                                    });
                              },
                              style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      const Color(0xfff07167))),
                              child: Text(
                                '确认出单',
                                style: TextStyle(
                                    fontSize: 35.sp, fontWeight: FontWeight.w600),
                              )),
                        ),
                      ),
                      Offstage(
                        offstage: forceChangeState,
                        child: Container(
                          padding: EdgeInsets.only(left: 100.w, right: 100.w),
                          margin: EdgeInsets.only(top: 25.h, ),
                          height: 40.h,
                          child: ElevatedButton(
                              onPressed: () {
                                showDialog(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return AlertDialog(
                                        title: Text(
                                          '⚠️注意',
                                          style: TextStyle(fontSize: 42.sp),
                                        ),
                                        content: Text(
                                          '重新抄表将清除本单数据,请确认操作',
                                          style: TextStyle(fontSize: 25.sp),
                                        ),
                                        actions: [
                                          TextButton(
                                              onPressed: () {
                                                //删除订单记录,重新抄表
                                                DatabaseHelper.instance
                                                    .deleteData(TableName.ORDER,
                                                        primaryKey: 'id',
                                                        primaryKeyValue:
                                                            orderVO!.id!);
                                                Navigator.pop(context);
                                                Navigator.pop(context);
                                              },
                                              child: Text(
                                                '确定',
                                                style: TextStyle(fontSize: 25.sp),
                                              )),
                                          TextButton(
                                              onPressed: () async {
                                                Navigator.pop(context);
                                              },
                                              child: Text(
                                                '返回',
                                                style: TextStyle(fontSize: 25.sp),
                                              )),
                                        ],
                                      );
                                    });
                              },
                              style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      const Color(0xff264653))),
                              child: Text(
                                '重新抄表',
                                style: TextStyle(
                                    fontSize: 25.sp,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.white70),
                              )),
                        ),
                      ),
                Offstage(
                  offstage: forceChangeState,
                  child: Container(
                    padding: EdgeInsets.only(left: 100.w, right: 100.w),
                    margin: EdgeInsets.only(top: 25.h, bottom: 100.h),
                    height: 40.h,
                    child: ElevatedButton(
                        onPressed: () {
                          showDialog(
                              context: context,
                              builder: (BuildContext context) {
                                return AlertDialog(
                                  title: Text(
                                    '⚠️注意',
                                    style: TextStyle(fontSize: 42.sp),
                                  ),
                                  content: Text(
                                    '非必要,请勿直接修改数据,以免造成数据错误.',
                                    style: TextStyle(fontSize: 25.sp),
                                  ),
                                  actions: [
                                    TextButton(
                                        onPressed: () {
                                          setState(() {
                                            forceChangeState = true;
                                            //初始化控制器
                                            _initalTextController();
                                          });
                                          Navigator.pop(context);
                                        },
                                        child: Text(
                                          '确定修改',
                                          style: TextStyle(fontSize: 25.sp),
                                        )),
                                    TextButton(
                                        onPressed: () async {
                                          Navigator.pop(context);
                                        },
                                        child: Text(
                                          '返回',
                                          style: TextStyle(fontSize: 25.sp),
                                        )),
                                  ],
                                );
                              });
                        },
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(
                                const Color(0xff264653))),
                        child: Text(
                          '⚠️强制修改',
                          style: TextStyle(
                              fontSize: 25.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.white70),
                        )),
                  ),
                ),
                Offstage(
                  offstage: !forceChangeState,
                  child: Container(
                    padding: EdgeInsets.only(left: 100.w, right: 100.w),
                    margin: EdgeInsets.only(top: 25.h, bottom: 100.h),
                    height: 40.h,
                    child: ElevatedButton(
                        onPressed: () {
                          setState(() {
                            forceChangeState = false;
                          });
                        },
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(
                                const Color(0xff264653))),
                        child: Text(
                          '确认修改',
                          style: TextStyle(
                              fontSize: 25.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.white70),
                        )),
                  ),
                )
                    ],
            )),
      ),
    );
  }

  void showSnackBar(BuildContext context) {
    const snackBar = SnackBar(
      content: Text('已保存到系统相册'),
      duration: Duration(seconds: 2), // Snackbar 显示的持续时间
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  createImg() async {

    //loading加载中动画
    showDialog(
      context: context,
      barrierDismissible: false,
      // Prevent dismissing the dialog by tapping outside
      builder: (BuildContext context) {
        return AlertDialog(
          content: Row(
            children: [
              const CircularProgressIndicator(),
              SizedBox(width: 16.w),
              const Text('处理中...'),
            ],
          ),
        );
      },
    );

    if (file == null) {
      // 创建一个临时文件
      final tempDirectory = (await getTemporaryDirectory()).path;
      file = File('$tempDirectory/bill.png');
      Uint8List? image = await screenshotController.capture(pixelRatio: 3);
      // 将截图数据写入临时文
      final imageFile = await file!.create();
      await imageFile.writeAsBytes(image!, flush: true);
    }
    Navigator.of(context).pop();
  }
}
